#include <dlfcn.h> 
#include <stdio.h> 
#include <stdlib.h>
#include <unistd.h>

/********** funcion de salida ANTES de EXIT *********/
void bye(void) 
{ 
printf("BYE: Funtion before exit\n"); 
} 

/************* funcion a ejecutar ANTES de MAIN *************/
void init(void) __attribute__ ((constructor));
void init(void) 
{ 
printf("\nINIT: function before main\n"); 
set_atexit(bye);
} 


/************* funcion a ejecutar DESPUES de MAIN *************/
void fini(void) __attribute__ ((destructor));
void fini(void) 
{ 
printf("\nFINI: function after main\n"); 
set_atexit(bye);
} 

/********* registra la funcion de salida ******/
int set_atexit(void (*function)(void))
{
	long a; 
	int i; 
	a = sysconf(_SC_ATEXIT_MAX); 
	printf("ATEXIT_MAX = %ld\n", a); 
	/***** tambien se puede usar int on_exit(void (*function)(int , void *), void *arg); ***/
	i = atexit(bye); 
	if (i != 0) 
		{ 
		fprintf(stderr, "cannot set exit function\n"); 
		return EXIT_FAILURE; 
		} 
	return EXIT_SUCCESS;
}

/***************falso GETPID *********************/
int getpid(void)  
{ 
	typedef int (*FP_getpid)(void); 

	/*get the address of the intercepted funcion */
	FP_getpid org_getpid = dlsym(((void *) -1l), "getpid"); 

	printf("FAKEPID: Original getpid returns = %d\n",org_getpid());

	return(3333); 
} 
